<?php
/**
 * 系统设置
 *
 * @author      wzx
 * @version     1.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\AdminCreateRequest;
use App\Http\Requests\ConfigUpdateRequest;
use App\Models\Config;
use App\Models\OperationLog;
use Illuminate\Http\Request;
use App\Http\Requests\AdminEditRequest;
use App\Http\Requests\RoleCreateRequest;
use App\Http\Requests\RoleEditRequest;
use App\Models\Admin;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Backup;

class SystemController extends Controller
{
    /*
     * 管理员设置
     * @return View
     */
    public function user()
    {
        $roles = Role::select('name')->get();
        return view('admin.system.user.user')->with('roles', $roles);
    }

    /*
     * 获取管理员数据
     * @return array
     */
    public function userData(Request $request)
    {
        $model = Admin::query();
        if ($request->get('username')) {
            $model->where('username', 'like', '%' . $request->get('username') . '%');
        }
        if ($request->get('name')) {
            $model->where('name', 'like', '%' . $request->get('name') . '%');
        }
        if ($request->get('phone')) {
            $model->where('phone', $request->get('phone'));
        }
        if ($request->get('email')) {
            $model->where('phone', $request->get('email'));
        }
        if ($request->get('role')) {
            $model->role($request->get('role'));
        }
        if ($request->get('status')) {
            $model->where('status', $request->get('status'));
        }
        $result = $model->orderBy('id', 'desc')
            ->paginate($request->get('limit', self::ADMIN_PAGE_NUM))->toArray();
        $result['data'] = $this->setAdminRole($result['data']);
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $result['total'],
            'data' => $result['data']
        ];
        return response()->json($data);
    }

    /*
     * 设置角色
     * @return array
     */
    private function setAdminRole($data)
    {
        foreach ($data as $key => $item) {
            $admin = Admin::find($item['id']);
            $role = $admin->getRoleNames();
            foreach ($role as $val) {
                $data[$key]['role'] = $val;
            }
        }
        return $data;
    }

    private function getAdminRoleName($admin)
    {
        $role = $admin->getRoleNames();
        $rl = '';
        foreach ($role as $val) {
            $rl = $val;
        }
        return $rl;
    }

    /*
     * 创建管理员页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function userCreateForm()
    {
        $roles = Role::get();
        return view('admin.system.user.create')->with('roles', $roles);
    }

    /*
     * 创建管理员
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function userCreate(AdminCreateRequest $request)
    {
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        $admin = Admin::create($data);
        $r = Role::where('id', '=', $data['role'])->firstOrFail();
        $admin->assignRole($r);
        return redirect()->to(route('admin.system.user'))->with(['status' => '添加账号成功']);
    }

    /*
     * 编辑管理员
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function userEditForm($id)
    {
        $admin = Admin::findOrFail($id);
        $roles = Role::get(); // 获取所有角色
        return view('admin.system.user.edit')
            ->with('roles', $roles)
            ->with('admin', $admin);
    }

    /*
     * 编辑管理员
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function userEdit(AdminEditRequest $request)
    {
        $id = $request->get('id');
        $admin = Admin::findOrFail($id);
        $admin->name = $request->get('name');
        $admin->email = $request->get('email');
        $admin->phone = $request->get('phone');
        if($request->get('password')){
            $admin->password = bcrypt($request->get('password'));
        }
        $admin->status = $request->status;
        $admin->save();
        $admin->roles()->detach();
        $admin->roles()->sync($request->get('role'));
        return redirect()->to(route('admin.system.user'))->with(['status' => '更新成功']);
    }

    /*
     * 设置用户状态
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function userStatusSet(Request $request)
    {
        if (!$request->get('id')) {
            return response()->json([
                'code' => 0,
                'msg' => '更新失败!',
            ]);
        }
        $id = $request->get('id');
        $admin = Admin::find($id);
        if ($admin->status == 1) {
            $admin->status = 2;
        } else {
            $admin->status = 1;
        }
        if (!$admin->save()) {
            return response()->json([
                'code' => 0,
                'msg' => '更新失败!',
            ]);
        }
        return response()->json([
            'code' => 0,
            'msg' => '更新成功!',
        ]);
    }
//===============================================角色管理===========================================
    /*
     * 角色管理
     * @return View
     */
    public function role()
    {
        return view('admin.system.role.role');
    }

    /*
     * 获取角色数据
     */
    public function roleData(Request $request)
    {
        $model = Role::query();
        if ($request->get('name')) {
            $model->where('name', 'like', '%' . $request->get('name') . '%');
        }
        $result = $model->orderBy('id', 'desc')
            ->paginate($request->get('limit', self::ADMIN_PAGE_NUM))->toArray();
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $result['total'],
            'data' => $result['data']
        ];
        return response()->json($data);
    }

    /*
     * 创建角色页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function roleCreateForm()
    {
        $permissions = Permission::where('pid',0)->orderBy('sort','asc')->get()->toArray();
        $data = array();
        foreach($permissions as $k=>$v){
             $data[$k]['title']=$v['power_name'];
             $data[$k]['id']=$v['id'];
             $data[$k]['checked']=true;
             $data[$k]['spread']=true;
            $data[$k]['field'] = "permissions[]";
             $erji = Permission::where('pid',$v['id'])->orderBy('sort','asc')->get()->toArray();
             foreach($erji as $k2=>$v2){
                $data[$k]['children'][$k2]['title']=$v2['power_name']; 
                $data[$k]['children'][$k2]['id']=$v2['id'];
                $data[$k]['children'][$k2]['checked']=true;
                $data[$k]['children'][$k2]['spread']=true;
                $data[$k]['children'][$k2]['field']="permissions[]"; 
                $sanji = Permission::where('pid',$v2['id'])->orderBy('sort','asc')->get()->toArray();
                foreach($sanji as $k3=>$v3){
                $data[$k]['children'][$k2]['children'][$k3]['title']=$v3['power_name']; 
                $data[$k]['children'][$k2]['children'][$k3]['id']=$v3['id'];
                $data[$k]['children'][$k2]['children'][$k3]['checked']=true;
                $data[$k]['children'][$k2]['children'][$k3]['spread']=true;
                $data[$k]['children'][$k2]['children'][$k3]['field']="permissions[]"; 
                }
             }
        }
//        $data = json_encode($data,JSON_UNESCAPED_UNICODE); 
        return view('admin.system.role.create')->with('data',$data);
    }

    /*
     * 创建角色
     * @return void
     */
    public function roleCreate(RoleCreateRequest $request)
    {
        $data = $request->all();
        $permissions = $data['permissions'];
        $role = Role::create([
            'name' => $data['name'],
            'guard_name' => 'admin',
            'description' => $data['description']
        ]);
        //$all = Permission::all()->pluck('id');
        $p = Permission::whereIn('id', $permissions)->pluck('id');
        //$role->revokePermissionTo($all);
        $role->givePermissionTo($p);
        return redirect()->to(route('admin.system.role'))->with(['status' => '创建成功']);
    }

    /*
     * 编辑角色页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function roleEditForm($id)
    {
        $role = Role::findOrFail($id);
        $permissions = Permission::where('pid',0)->orderBy('sort','asc')->get()->toArray();
        $role_permissions=array_column($role->permissions->toarray(), 'name','id');
//        var_dump(isset($role_permissions['16'])?"true":"false");exit;
        $data = array();
        foreach($permissions as $k=>$v){
             $data[$k]['title']=$v['power_name'];
             $data[$k]['id']=$v['id'];
             $data[$k]['checked']=isset($role_permissions[$v['id']])?true:false;
             $data[$k]['spread']=true;
            $data[$k]['field'] = "permissions[]";
             $erji = Permission::where('pid',$v['id'])->orderBy('sort','asc')->get()->toArray();
             foreach($erji as $k2=>$v2){
                $data[$k]['children'][$k2]['title']=$v2['power_name']; 
                $data[$k]['children'][$k2]['id']=$v2['id'];
                $data[$k]['children'][$k2]['checked']=isset($role_permissions[$v2['id']])?true:false;
                $data[$k]['children'][$k2]['spread']=true;
                $data[$k]['children'][$k2]['field']="permissions[]"; 
                $sanji = Permission::where('pid',$v2['id'])->orderBy('sort','asc')->get()->toArray();
                foreach($sanji as $k3=>$v3){
                $data[$k]['children'][$k2]['children'][$k3]['title']=$v3['power_name']; 
                $data[$k]['children'][$k2]['children'][$k3]['id']=$v3['id']; 
                $data[$k]['children'][$k2]['children'][$k3]['checked']= isset($role_permissions[$v3['id']])?true:false;
                 $data[$k]['children'][$k2]['children'][$k3]['spread']= true;
                $data[$k]['children'][$k2]['children'][$k3]['field']="permissions[]"; 
                 }
               }
            }
        return view('admin.system.role.edit')
            ->with('data', $data)
            ->with('role', $role);
    }

    /*
     * 编辑角色
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function roleEdit(RoleEditRequest $request)
    {
        $id = $request->get('id');
        $role = Role::findOrFail($id);
        $request->except(['permissions']);
        $permissions = $request->get('permissions');
        $role->name = $request->get('name');
        $role->guard_name = 'admin';
        $role->description = $request->get('description');
        $role->save();
        $all = Permission::all()->pluck('id');
        $role->revokePermissionTo($all);
        foreach ($permissions as $permission) {
            $p = Permission::where('id', '=', $permission)->firstOrFail(); //从数据库中获取相应权限
            $role->givePermissionTo($p);  // 分配权限到角色
        }
        return redirect()->to(route('admin.system.role'))->with(['status' => '更新成功']);
    }

//===============================================权限管理===========================================
    /*
     * 权限管理
     * @return View
     */
    public function permission(Request $request)
    {
        return view('admin.system.permission.index');
    }

    /*
     * 获取权限数据
     */
    public function permissionData(Request $request)
    {
        $model = Permission::where('pid',0);
        if ($request->get('name')) {
            $model->where('name', 'like', '%' . $request->get('name') . '%');
        }
        $result = $model->orderBy('sort', 'asc')
            ->paginate($request->get('limit', self::ADMIN_PAGE_NUM))->toArray();
        
        foreach($result['data'] as $k=>$v){
              $erji = Permission::where('pid',$v['id'])->orderBy('sort','asc')->get()->toArray();
              foreach($erji as $k2=>$v2){
                  $v2['power_name']='&nbsp;'.$v2['power_name'];
                  $v2['p_power_name']=$v['power_name'];
                 $result['data'][]=$v2;
                  $sanji = Permission::where('pid',$v2['id'])->orderBy('sort','asc')->get()->toArray();
                  foreach($sanji as $k3=>$v3){
                   $v3['power_name']='&nbsp;&nbsp;'.$v3['power_name'];
                   $v3['p_power_name']=$v2['power_name'];
                   $result['data'][]=$v3;
                  }
              }
        }
//       var_dump($result['data']);
//       exit;
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $result['total'],
            'data' => $result['data']
        ];
        return response()->json($data);
    }

    /*
     * 创建权限页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permissionCreateForm(Request $request)
    {
        $pid = $request->get('pid');
        return view('admin.system.permission.create')->with('pid',$pid);
    }

    /*
     * 创建权限
     * @return void
     */
    public function permissionCreate(Request $request)
    {
        $data = $request->all();
        Permission::create([
            'name' => $data['name'],
            'power_name' => $data['power_name'],
            'pid' => empty($data['pid'])?0:$data['pid'],
            'sort' => $data['sort'],
            'guard_name' =>'admin'
        ]);
        return redirect()->to(route('admin.system.permission'))->with(['status' => '创建成功']);
    }

    /*
     * 编辑权限页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permissionEditForm($id)
    {
        $permission = Permission::findOrFail($id);
        return view('admin.system.permission.edit')
            ->with('permission', $permission);
    }

    /*
     * 编辑权限
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permissionEdit(Request $request)
    {
        $id = $request->get('id');
        $permission = Permission::findOrFail($id);
        $permission->name = $request->get('name');
        $permission->power_name = $request->get('power_name');
        $permission->sort = $request->get('sort');
        $permission->guard_name = 'admin';
        $permission->save();
        return redirect()->to(route('admin.system.permission'))->with(['status' => '更新成功']);
    }



//===========================================数据库备份===================================================

    /*
     * 数据库备份
     * @return View
     */
    public function backup()
    {
        return view('admin.system.database.backup');
    }

    /*
     * 获取数据库备份数据
     * @return View
     */
    public function backupData(Request $request)
    {
        $model = Backup::query();
        $result = $model->orderBy('id', 'desc')
            ->paginate($request->get('limit', self::ADMIN_PAGE_NUM))->toArray();
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $result['total'],
            'data' => $result['data']
        ];
        return response()->json($data);
    }

    /*
     * 交数据库备份 删除
     * @return http response
     */
    public function backupDelete(Request $request)
    {
        if (!$request->get('id')) {
            return response()->json([
                'code' => self::RESPONSE_CODE_ERROR,
                'msg' => '删除失败!',
            ]);
        }
        $id = $request->get('id');
        $result = Backup::destroy($id);
        if ($result) {
            return response()->json([
                'code' => self::RESPONSE_CODE_SUCCESS,
                'msg' => '删除成功!',
            ]);
        }
        return response()->json([
            'code' => self::RESPONSE_CODE_ERROR,
            'msg' => '删除失败!',
        ]);
    }

    /**
     * 获取数据库备份数据
     * @return http response
     */
    public function backupExecute()
    {
        return response()->json([
            'code' => self::RESPONSE_CODE_SUCCESS,
            'msg' => '备份成功!',
        ]);
    }

    /**
     * 操作记录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function log()
    {
        return view('admin.system.log.index');
    }

    /*
     * 操作记录列表
     * @return json
     */
    public function getLogs(Request $request)
    {
        $logs = OperationLog::query();
        $logs->leftJoin('admin', 'operation_logs.user_id', '=', 'admin.id');
        $result = $logs->orderBy('operation_logs.id', 'desc')
            ->paginate($request->get('limit', self::ADMIN_PAGE_NUM))->toArray();
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $result['total'],
            'data' => $result['data']
        ];
        return response()->json($data);
    }

    /*
     * 站点配置
     * @return view
     */
    public function config()
    {
        $config = Config::query();
        $data = $config->first();
        return view('admin.system.config.index')
            ->with('config', $data);
    }

    /*
     * 站点配置 更新
     * @return json
     */
    public function configUpdate(ConfigUpdateRequest $request)
    {
        $config = Config::query();
        $config = $config->first();
        if (!$config) {
            Config::create([
                'name' => $request->get('name'),
                'description' => $request->get('description'),
                'code' => $request->get('code'),
                'tel' => $request->get('tel'),
                'email' => $request->get('email'),
                'address' => $request->get('address'),
                'keyword' => $request->get('keyword')
            ]);
            return redirect()->to(route('admin.system.config'))->with(['status' => '配置成功']);
        } else {
            $config->name = $request->get('name');
            $config->description = $request->get('description');
            $config->code = $request->get('code');
            $config->tel = $request->get('tel');
            $config->email = $request->get('email');
            $config->address = $request->get('address');
            $config->keyword = $request->get('keyword');
            $config->save();
        }

        return redirect()->to(route('admin.system.config'))->with(['status' => '配置成功']);
    }
}